package com.mjf.ys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mjf.ys.domain.FsYsProductClass;
import com.mjf.ys.domain.FsYsSalesoutDetail;
import com.mjf.ys.domain.FsYsSalesoutList;
import com.mjf.ys.enums.YSApiEnum;
import com.mjf.ys.mapper.FsYsSalesoutListMapper;
import com.mjf.ys.service.FsYsSalesoutListService;
import com.mjf.ys.service.IFsYsSalesoutDetailService;
import com.mjf.ys.util.YSSendUtil;
import com.mjf.ys.vo.ProductClassVO;
import com.mjf.ys.vo.SalesoutDetailVO;
import com.mjf.ys.vo.SalesoutListVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * desc
 * </p>
 *
 * @author chenshoumeng
 * @date 2025/6/20 14:04
 */
@Slf4j
@Service
public class FsYsSalesoutListServiceImpl extends ServiceImpl<FsYsSalesoutListMapper, FsYsSalesoutList>
    implements FsYsSalesoutListService {

    @Autowired
    private YSSendUtil ysSendUtil;
    @Autowired
    private IFsYsSalesoutDetailService fsYsSalesoutDetailService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void asyncSalesout(String start, String end) {
        // 1. 定义格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        List<SalesoutListVO.ContentVO> datas = new ArrayList<>();
        String sendUrl = ysSendUtil.getSendUrl(YSApiEnum.YS_API_SALE_DELIVERY_LIST_URL);
        String sendDetailUrl = ysSendUtil.getSendUrl(YSApiEnum.YS_API_SALE_DELIVERY_DETAIL_URL);

        Map<String, Object> resMap = new HashMap<>();
        log.info("销售出库单，开始 {} ", sendUrl);
        resMap.put("pageSize", 500);
        resMap.put("totalCount", 10000);
        if (start != null && end != null) {
            resMap.put("vouchdate", start + "|" + end);
        }
        int i = 1;
        boolean  flag = true;
        List<FsYsSalesoutList> all = new ArrayList<>();
        List<FsYsSalesoutDetail> allDetails = new ArrayList<>();
        while (flag) {
            log.info(" 第 {} 页 ", i);
            resMap.put("pageIndex", i);
            try {
                String repsp = ysSendUtil.reqForResp(sendUrl, resMap);
                System.out.println(repsp);
                // 解析接口
                SalesoutListVO classVO = JSON.parseObject(repsp, SalesoutListVO.class);
                if (classVO.getCode().equals("200") && CollectionUtil.isNotEmpty(classVO.getData().getRecordList())) {
                    datas.addAll(classVO.getData().getRecordList());
                } else {
                    log.error("销售出库单结束，接口返回结果：{}", JSON.toJSONString(classVO));
                    flag = false;
                }
                i ++;
            } catch (Exception e) {
                log.error("销售出库单异常", e);
                flag = false;
            }
        }
        if (CollectionUtils.isNotEmpty(datas)) {
            for (SalesoutListVO.ContentVO vo : datas) {
                FsYsSalesoutList salesoutList = new FsYsSalesoutList();
                salesoutList.setId(vo.getId());
                salesoutList.setCode(vo.getCode());
                salesoutList.setCreceiveAddress(vo.getCReceiveAddress());
                if (StrUtil.isNotBlank(vo.getVouchdate())) {
                    // 2. 先转为 LocalDateTime
                    LocalDateTime dateTime = LocalDateTime.parse(vo.getVouchdate(), formatter);
                    salesoutList.setVouchdate(dateTime.toLocalDate());
                }
                salesoutList.setCreceiveMobile(vo.getCReceiveMobile());
                salesoutList.setCreceiver(vo.getCReceiver());
                salesoutList.setDepartmentName(vo.getDepartment_name());
                salesoutList.setOperatorName(vo.getOperator_name());
                salesoutList.setOperator(vo.getOperator());
                salesoutList.setDepartment(vo.getDepartment());
                salesoutList.setCustName(vo.getInvoiceCust_name());
                salesoutList.setCust(vo.getCust());
                salesoutList.setKh0002(vo.getSalesOutDefineCharacter().getKH0002());
                salesoutList.setShkh(vo.getSalesOutDefineCharacter().getSHKH());
                salesoutList.setXs00003(vo.getSalesOutDefineCharacter().getXS00003());
                salesoutList.setKh001(vo.getSalesOutDefineCharacter().getKh001());
                all.add(salesoutList);
            }
            for (FsYsSalesoutList salesoutList : all) {
                // 查询详情
                MultiValueMap<String, String> detailParam = new LinkedMultiValueMap<>();
                detailParam.add("id", salesoutList.getId().toString());
                String detailRepsp = ysSendUtil.reqForGetWithParam(sendDetailUrl, detailParam);
                // 解析接口
                SalesoutDetailVO detailVOs = JSON.parseObject(detailRepsp, SalesoutDetailVO.class);
                if (CollectionUtil.isNotEmpty(detailVOs.getData().getDetails())) {
                    for (SalesoutDetailVO.DetailVO detailVO : detailVOs.getData().getDetails()) {
                        FsYsSalesoutDetail salesoutDetail = new FsYsSalesoutDetail();
                        salesoutDetail.setDetailsId(salesoutList.getId());
                        salesoutDetail.setSalesoutListId(salesoutList.getCode());
                        salesoutDetail.setDetailsProduct(detailVO.getProduct());
                        salesoutDetail.setProductCcode(detailVO.getProduct_cCode());
                        salesoutDetail.setProductCname(detailVO.getProduct_cName());
                        salesoutDetail.setNatsum(detailVO.getNatsum());
                        salesoutDetail.setNatmoney(detailVO.getNatmoney());
                        salesoutDetail.setNattax(detailVO.getNattax());
                        salesoutDetail.setUnitname(detailVO.getUnitname());
                        salesoutDetail.setTaxrate(detailVO.getTaxrate());
                        salesoutDetail.setNattaxunitprice(detailVO.getNattaxunitprice());
                        salesoutDetail.setNatunitprice(detailVO.getNatunitprice());
                        salesoutDetail.setQty(detailVO.getQty());
                        salesoutDetail.setXs00004(detailVO.getSalesOutsDefineCharacter().getXS00004());
                        salesoutDetail.setYfdj(detailVO.getSalesOutsDefineCharacter().getYfdj());
                        salesoutDetail.setXs00014(detailVO.getSalesOutsDefineCharacter().getXS00014());
                        salesoutDetail.setCostUnitPrice(detailVO.getCostUnitPrice());
                        salesoutDetail.setCostMoney(detailVO.getCostMoney());
                        allDetails.add(salesoutDetail);
                    }
                }
            }
            saveOrUpdateBatch(all);
            fsYsSalesoutDetailService.saveOrUpdateBatch(allDetails);
        }
        log.info("销售出库单结束,处理数据：{}", datas.size());

    }
}
